const path = require("path");
const fs = require("fs");

/**
 * 生成文件夹名称
 * @return {string}
 */
function getUploadDirName() {
  const date = new Date();
  let month = date.getMonth() + 1;
  month = month > 9 ? month : `0${month}`;
  return `${date.getFullYear()}${month}${date.getDate()}`;
}

/**
 * 生成文件名称
 * @param filename
 * @return {string}
 */
function generateFileName(filename) {
  const exten = getUploadFileExt(filename);
  const name = filename.replace(`.${exten}`, "");
  return `${name}-${new Date().getTime()}.${exten}`;
}

/**
 * 创建文件夹
 * @param filePath 文件路径
 * @param {Number} [mode = 0o777] 文件权限
 */
function createMkdirSync(filePath, mode = 0o777) {
  try {
    if (fs.existsSync(filePath)) return true;
    let pathtmp = "";
    filePath.split(/[/\\]/).forEach(function(dirname) {
      pathtmp = pathtmp ? path.join(pathtmp, dirname) : dirname;
      if (!fs.existsSync(pathtmp)) {
        if (!fs.mkdirSync(pathtmp, mode)) {
          return false;
        }
      }
    });
    return true;
  } catch (e) {
    console.error("创建文件夹失败! path=" + filePath + " ，原因:" + e);
    return false;
  }
}

/**
 * 获取文件扩展名
 * @param name
 * @return {*|string}
 */
function getUploadFileExt(name) {
  const ext = name.split(".");
  return ext[ext.length - 1];
}

module.exports = {
  getUploadDirName,
  createMkdirSync,
  getUploadFileExt,
  generateFileName
};
